const watchers: Map<String, ((value: number) => void)[]> = new Map()
const counters: Map<String, number> = new Map()
const settings: Map<String, CounterSetting> = new Map()
//默认寄数器配置
export function useDefaultCounterSetting(prefix = 'afast-count'): CounterSetting {
  return {
    get() {
      if (!this.counterName) return 0
      const v = localStorage.getItem(`${prefix}-${this.counterName}`)
      if (!v) return 0
      return Number(v)
    },
    set(v: number) {
      if (!this.counterName) return
      localStorage.setItem(`${prefix}-${this.counterName}`, v + '')
    }
  }
}
//监听寄数器
export function watchCount(name: string, callback: (value: number) => void) {
  if (!watchers.has(name)) {
    watchers.set(name, [])
  }
  watchers.get(name)?.push(callback)
}
//注册寄数器
export function registerCounter(name: string, setting: CounterSetting) {
  {
    //@ts-ignore
    setting.counterName = name
    settings.set(name, setting)
  }
}
//获取寄器值
export function getCount(name: String) {
  return settings.get(name)?.get()
}
//设置寄数器值
export function setCount(name: String, value: number) {
  const setting = settings.get(name)
  counters.set(name, value)
  if (setting) setting.set(value)
  watchers.get(name)?.forEach(callback => {
    callback(value)
  })
}
//寄数器值自增
export function increaseCount(name: String) {
  const setting = settings.get(name)
  if (!counters.has(name)) {
    let newValue = 1;
    if (setting) {
      newValue = setting.get() + 1
      setting.set(newValue)
    }
    counters.set(name, newValue)
  } else {
    const newValue = (counters.get(name) as number) + 1
    if (setting) setting.set(newValue)
    counters.set(name, newValue)
  }
  watchers.get(name)?.forEach(callback => {
    callback(counters.get(name) as number)
  })
}